package com.zang.blogz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zang.blogz.constant.ResultConstant;
import com.zang.blogz.entity.Article;
import com.zang.blogz.entity.Category;

import com.zang.blogz.mapper.CategorMapper;
import com.zang.blogz.model.output.admin.AdminCategoryVO;
import com.zang.blogz.model.output.TagArticleVO;
import com.zang.blogz.model.output.CategoryListVO;
import com.zang.blogz.model.output.CategoryVO;
import com.zang.blogz.result.Result;
import com.zang.blogz.service.ArticleService;
import com.zang.blogz.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.github.vampireachao.stream.core.optional.Opp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 朵橙i
 * @since 2022-06-17
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategorMapper, Category> implements CategoryService {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CategorMapper categorMapper;

    @Override
    public CategoryVO getCategoryList() {

        ArrayList<CategoryListVO> categoryListVos = new ArrayList<>();
        List<Category> list = list();

        list.forEach(category -> categoryListVos.add(CategoryListVO.builder().id(category.getId())
                .count(articleService.count(new LambdaQueryWrapper<Article>().eq(Article::getCategoryId, category.getId())))
                .categoryName(category.getCategoryName()).build()));

        return CategoryVO.builder().categoryCount(count())
                .categoryListVo(categoryListVos).build();
    }

    @Override
    public List<TagArticleVO> getCategoryArticleVoById(Integer categoryId) {

        return categorMapper.getCategoryArticleVoById(categoryId);
    }


    public String getCategoryNameByCategoryId(Integer id) {

        return getById(id).getCategoryName();
    }

    @Override
    public IPage<AdminCategoryVO> getCategoryPage(String categoryName, Page<Category> page) {

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(categoryName), Category::getCategoryName, categoryName);

        Page<Category> categoryPage = page(page, queryWrapper);

        Map<Integer, Integer> integerMap = articleService.getArticleCount();

        return categoryPage.convert(result -> {
            AdminCategoryVO vo = new AdminCategoryVO();

            vo.setCount(integerMap.get(result.getId()));
            vo.setCanEdit(Boolean.TRUE);
            vo.setCanDelete(Boolean.FALSE);
            BeanUtil.copyProperties(result, vo);
            return vo;
        });
    }

    @Override
    public Result<Category> editOrSaveCategory(Category category) {

        if (category.getId() == null) {

            save(category);
            return Result.ok(ResultConstant.SAVE_SUCCESS, category);
        }

        Category categoryOld = getById(category.getId());
        if (categoryOld == null) {

            throw new RuntimeException(String.format("id为{%d}的标签不存在无法编辑", category.getId()));
        }

        updateById(category);
        return Result.ok(ResultConstant.UPDATE_SUCCESS, category) ;
    }

    @Override
    public Result<String> deleteCategoryById(Integer categoryId) {

        Opp.of(getById(categoryId)).orElseThrow(()-> new RuntimeException(String.format("id为{%d}的标签不存在无法删除", categoryId)));


        long refCount = articleService.getArticleCountByCategoryId(categoryId);
        if (refCount > 0) {

            Result.error(String.format("id为{%d}的标签有关联文章无法删除", categoryId));
        }

        removeById(categoryId);
        return Result.ok(ResultConstant.DELETE_SUCCESS);
    }

}
